<template>
  <div class="app-container">
    <div class="form-box">
      <el-form ref="form" :model="form" label-width="120px" :rules="rules">
        <el-tabs type="border-card" class="form-tabs">
          <el-tab-pane :label="$t('common.basic_info')" class="form-tabs-tab-pane">

            <!-- 开关 -->
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item :label="$t('form.switch')" prop="switch">
                  <el-switch v-model.number="form.switch" :active-value="1" :inactive-value="0" />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 联级分类 -->
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item :label="$t('form.category_id')" prop="cascader_category_ids">
                  <el-cascader
                    v-model="form.cascader_category_ids"
                    :options="cascaderCategoryTreeData"
                    :props="{ checkStrictly: true, children: 'children', label: 'name', value: 'id'}"
                    :placeholder="$t('form.category_id_tips')"
                    filterable
                    clearable
                    @change="handleCascaderCategoryTreeChange"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 单行文本：标题 -->
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item :label="$t('form.title')" prop="title">
                  <el-input v-model="form.title" :placeholder="$t('form.title_tips')" clearable />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 带拖拽排序的图片上传组件：封面图 -->
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item
                  :label="$t('form.cover_image')"
                  prop="cover_image"
                >
                  <jsp-image-upload
                    :title="$t('form.cover_image')"
                    :limit="1"
                    :default-list="cover_imageList"
                    :action="fileUploadConfig.imageAction"
                    :headers="fileUploadConfig.headers"
                    :size="Number(fileUploadConfig.allowImageSize)"
                    :accept="fileUploadConfig.allowImageTypeList"
                    @dragStart="handleDragImageStart"
                    @dragEnd="handleDragImageEnd"
                    @remove="handleImageDelete"
                    @error="(error)=>{error!=null && $message.error(error)}"
                    @change="handleImageUploadChange"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 标签：关键词 -->
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item :label="$t('form.keywords')" prop="keywords">
                  <jsp-tags
                    ref="JspTags"
                    :data="form.keywords"
                    :limit="20"
                    @change=" (tags) => form.keywords = tags "
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 多行文本：摘要 -->
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item :label="$t('form.description')" prop="desc">
                  <el-input v-model="form.description" type="textarea" :placeholder="$t('form.description_tips')" />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 富文本编辑器：内容 -->
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item :label="$t('form.content')" prop="content">
                  <jsp-ckeditor
                    id="content"
                    v-model="form.content"
                    :config="{
                      'filebrowserUploadUrl': fileUploadConfig.action,
                      'filebrowserImageUploadUrl': fileUploadConfig.imageAction,
                      'headers' : fileUploadConfig.headers,
                      'filebrowserUploadInputName': 'file',
                      'uploadFileDomain' : fileUploadConfig.uploadFileDomain,
                    }"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 下拉选项：发布状态 -->
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item
                  :label="$t('form.status')"
                  prop="status"
                >
                  <el-select
                    v-model.number="form.status"
                    :placeholder="$t('form.status_tips')"
                    clearable
                  >
                    <el-option
                      v-for="item in dictionaryService.getItems('statusVar')"
                      :key="item.id"
                      :label="item.name"
                      :value="Number(item.value)"
                    />

                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 单选框：类型 -->
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item :label="$t('form.type')" prop="type">
                  <el-radio-group v-model.number="form.type" :placeholder="$t('form.type_tips')">
                    <el-radio v-for="item in dictionaryService.getItems('infoCategoryTypeVar')" :key="item.id" :label="Number(item.value)">{{ item.name }}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 复选框：推荐类型 -->
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item
                  :label="$t('form.recommend_type')"
                  prop="recommend_type"
                >
                  <el-checkbox-group v-model="form.recommend_type">
                    <el-checkbox v-for="item in dictionaryService.getItems('recommendTypeVar')" :key="item.id" :label="item.value">{{ item.name }}</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 时间选项：创建时间 -->
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item
                  :label="$t('form.created_at')"
                  prop="created_at"
                >
                  <el-date-picker
                    v-model="form.created_at"
                    type="datetime"
                    :placeholder="$t('form.created_at_tips')"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    :editable="false"
                    clearable
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 时间范围： 投放开始时间-投放结束时间 -->
            <el-row
              :gutter="20"
              type="flex"
              justify="center"
            >
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item
                  :label="$t('form.daterange')"
                  prop="daterange"
                >
                  <el-date-picker
                    v-model="form.daterange"
                    type="datetimerange"
                    :range-separator="$t('common.rangeTo')"
                    :start-placeholder="$t('common.start_time')"
                    :end-placeholder="$t('common.end_time')"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    format="yyyy-MM-dd HH:mm:ss"
                    clearable
                    :editable="false"
                    @change="timeChange"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 多文件上传 -->
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item :label="$t('common.uploadFile')" prop="file_ids">
                  <jsp-file-upload
                    :default-list="default_fileList"
                    :action="fileUploadConfig.action"
                    :headers="fileUploadConfig.headers"
                    :limit="5"
                    :size="2"
                    :accept="fileUploadConfig.allowTypeList"
                    @remove="handleFileDelete"
                    @change="handleFileUploadChange"
                    @preview="handleFileUploadPreview"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 多选：分类树 -->
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item :label="$t('form.tree')" prop="tree">
                  <el-scrollbar>
                    <el-tree
                      ref="tree"
                      :check-strictly="false"
                      :data="treeDemoData"
                      :props="{ children: 'children', label: 'name' }"
                      show-checkbox
                      node-key="id"
                      class="permission-tree"
                      :default-checked-keys="form.tree"
                      :empty-text="empty_text"
                      @check="handleNodeCheck"
                    />
                  </el-scrollbar>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 级联选择器：省市县 -->
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item :label="$t('form.cascader')" prop="cascaderValue">
                  <el-cascader
                    v-model="form.cascaderValue"
                    :options="cascaderOptions"
                    :props="{ expandTrigger: 'hover' }"
                    :clearable="true"
                    :filterable="true"
                    :debounce="300"
                    @change="handleCascaderChange"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 图标选择器 -->
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item :label="$t('form.icon')" prop="icon">
                  <jsp-icon-picker v-model="form.icon" :placeholder="$t('form.icon_tips')" />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 复制内容 -->
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item :label="$t('form.copyInput')" prop="href">
                  <el-input v-model="form.href" :placeholder="$t('form.copyInput_tips')" clearable>
                    <el-button
                      slot="append"
                      icon="awesome-icon far fa-copy"
                      :title="$t('common.copy')"
                      @click="handleClipboard(form.href, $event)"
                    />
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 计数器1 -->
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item :label="$t('form.counts')" prop="counts">
                  <el-input-number v-model="form.counts" :min="1" :max="10" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane :label="$t('form.goods_info')" class="form-tabs-tab-pane">
            <!-- 图集 -->
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
                <el-form-item
                  :label="$t('common.picture')"
                  prop="image_list"
                >
                  <jsp-image-upload
                    :title="$t('common.picture')"
                    :default-list="default_image_list"
                    :action="fileUploadConfig.imageAction"
                    :headers="fileUploadConfig.headers"
                    :size="Number(fileUploadConfig.allowImageSize)"
                    :accept="fileUploadConfig.allowImageTypeList"
                    :limit="image_list_upload_limit"
                    :edit-desc="true"
                    @error="(error)=>{error!=null && $message.error(error)}"
                    @change="handleImageListUploadChange"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>

        </el-tabs>

        <el-row :gutter="20" type="flex" justify="center" class="btn-row">
          <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
            <el-form-item>
              <el-button
                type="primary"
                :loading="submitLoading"
                :disabled="routerParams.id>0&&!checkPermission(['admin.exampleTable.update']) || !routerParams.id&&!checkPermission(['admin.exampleTable.store'])"
                @click="onSubmit"
              >{{ $t('common.create') }}</el-button>
              <el-button @click="onCancel">{{ $t('common.cancel') }}</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import JspCkeditor from '@/components/JspCkeditor'
import JspIconPicker from '@/components/JspIconPicker'
import JspImageUpload from '@/components/JspImageUpload'
import clipboard from '@/utils/clipboard'
import JspFileUpload from '@/components/JspFileUpload'
import JspTags from '@/components/JspTags'
import { mapGetters } from 'vuex'
import { loadingStart } from '@/utils/loading-service'
import { show, update, store } from '@/api/example/table'
import { getTreeConfig } from '@/api/example/tree-table'
import checkPermission from '@/utils/permission'

// export
export default {
  name: 'TableEdit',
  components: {
    JspCkeditor,
    JspIconPicker,
    JspImageUpload,
    JspFileUpload,
    JspTags
  },
  data() {
    return {
      submitLoading: false,
      empty_text: this.$t('common.loading'),
      form: {
        category_id: 1, // 弹框分类树
        cascader_category_ids: [],
        switch: 1,
        title: '',
        cover_image: 2, // 图片
        keywords: [],
        description: '',
        content: '', // 编辑器
        created_at: '',
        recommend_type: [],
        status: 1,
        start_time: '',
        end_time: '',
        daterange: [],
        type: 1,
        tree: [], // 普通分类树id集
        file_ids: '', // 附件id集
        cascaderValue: ['0', '0', '0'], // [省id,市id，县id]
        province_id: 0, // 省
        city_id: 0, // 市
        county_id: 0, //  县
        icon: '', // 图标
        href: 'http://www.jishupu.com',
        counts: 0, // 计数器
        image_list: [] // 图集
      },
      cover_imageList: [], // 默认图片列表
      // 图集
      default_image_list: [],
      image_list_upload_limit: 15,
      // 默认附件列表
      default_fileList: [],
      // 表单填写校验 ，通过prop="name"属性进行控制
      rules: {
        title: [
          { required: true, message: this.$t('form.title_tips'), trigger: 'blur' },
          { min: 2, max: 50, message: this.$t('form.title_length_tips'), trigger: 'blur' }
        ],
        cover_image: { required: true, pattern: /^[1-9]{1}[0-9]{0,}$/, message: this.$t('common.cover_image_tips'), trigger: ['change'] },
        daterange: [
          {
            required: true,
            type: 'array',
            message: this.$t('form.daterange_tips'),
            trigger: 'blur',
            fields: {
              0: {
                required: true,
                trigger: 'blur',
                message: this.$t('form.daterange_start_time_tips')
              },
              1: {
                required: true,
                trigger: 'blur',
                message: this.$t('form.daterange_end_time_tips')
              }
            }
          }
        ],
        cascader_category_ids: { required: true, message: this.$t('form.category_id_tips'), trigger: ['change'] }
      },
      // 分类树数据
      treeDemoData: [],
      // 级联选择器数据
      cascaderOptions: [
        {
          value: 0,
          label: '全部',
          children: [
            {
              value: 0,
              label: '全部',
              children: [
                {
                  value: 0,
                  label: '全部'
                }
              ]
            }
          ]
        },
        {
          value: 1,
          label: '北京市',
          children: [
            {
              value: 0,
              label: '全部'
            },
            {
              value: 1,
              label: '北京市',
              children: [
                {
                  value: 0,
                  label: '全部'
                },
                {
                  value: 11,
                  label: '朝阳区'
                },
                {
                  value: 12,
                  label: '顺义区'
                }
              ]
            }
          ]
        }
      ],
      // 联级分类数据
      cascaderCategoryTreeData: [],
      // 路由参数
      routerParams: {},
      back_route_name: 'TableIndex'
    }
  },
  computed: {
    ...mapGetters(['fileUploadConfig'])
  },
  created() {
    this.routerParams = this.$route.params
  },
  mounted() {
    this.getDetail()
  },
  methods: {
    /** *********************************************** 表单相关 开始 ******************************************************/
    checkPermission,
    async getDetail() {
      const loading = loadingStart()
      const { id } = this.routerParams
      if (id > 0) {
        const { data } = await show(id).catch(() => {
          this.closeBack(this.back_route_name)
        })

        for (const key in data) {
          if (key in this.form) {
            this.form[key] = data[key] !== undefined ? data[key] : this.form[key]
          }
        }

        // 封面图
        this.cover_imageList = this.form.cover_image
        this.form.cover_image = this.form.cover_image.map((item) => {
          return item.id
        }).join(',')

        // 文件列表
        this.default_fileList = this.form.file_ids
        this.form.file_ids = this.form.file_ids.map((item) => {
          return item.id
        }).join(',')

        // 时间范围
        this.form.daterange = [
          this.form.start_time,
          this.form.end_time
        ]

        // 省市县联动
        this.form.cascaderValue = [
          this.form.province_id,
          this.form.city_id,
          this.form.county_id
        ]

        // 图集
        this.default_image_list = this.form.image_list ?? []
      }

      // 弹框分类、分类树配置
      await getTreeConfig().then((response) => {
        const { items } = response.data
        this.treeDemoData = this.cascaderCategoryTreeData = items
        if (this.treeDemoData.length === 0) this.empty_text = this.$t('common.empty')
      }).catch(() => {})

      // 分类树默认值
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys(this.form.tree)
      })

      loading.close()
    },
    // 提交表单
    onSubmit() {
      this.$refs['form'].validate(async(valid) => {
        if (valid) {
          this.submitLoading = true
          let response
          const newForm = JSON.parse(JSON.stringify(this.form))
          delete newForm.daterange
          delete newForm.cascaderValue
          delete newForm.cascader_category_ids
          if (this.routerParams.id) {
            response = await update(this.routerParams.id, newForm).catch(() => {})
          } else {
            response = await store(newForm).catch(() => {})
          }
          if (response instanceof Object) {
            this.$message.success(response.message)
            this.closeBack(this.back_route_name)
          }
          this.submitLoading = false
        } else {
          this.$message.error(this.$t('common.pleaseFillRequired'))
          return false
        }
      })
    },
    // 取消/返回
    onCancel() {
      this.closeBack(this.back_route_name)
    },
    // 文件删除
    handleFileDelete(file, fileList) {
      console.log('删除事件')
    },
    // 文件上传成功、删除文件时激活
    handleFileUploadChange(result) {
      console.log('改变事件', result)
      this.form.file_ids = result.ids
    },
    // 文件预览或下载
    handleFileUploadPreview(file) {
      console.log('点击预览或下载', file)
    },
    // 图片拖拽开始
    handleDragImageStart(e, fileList) {
      console.log('开始拖拽事件', e, fileList)
    },
    // 图片拖拽结束
    handleDragImageEnd(e, fileList) {
      console.log('拖拽结束事件', e, fileList)
    },
    // 删除图片
    handleImageDelete(file, fileList) {
      console.log('删除图片事件', file, fileList)
      this.$message.success('删除成功')
      this.$refs['form'].validateField(['cover_image'])
    },
    // 上传成功、上传失败、拖拽结束时返回当前的图片数组、图片id集
    handleImageUploadChange(result) {
      this.form.cover_image = result.ids
      this.$refs['form'].validateField(['cover_image'])
      this.form.cover_image && this.$refs['form'].clearValidate(['cover_image'])
    },
    // 联动：省市县
    handleCascaderChange(value) {
      this.form.province_id = value[0]
      this.form.city_id = value[1]
      this.form.county_id = value[2]
    },
    // 复制
    handleClipboard(text, event) {
      clipboard(text, event)
    },
    // 投放时间范围选择
    timeChange(e) {
      this.form.start_time = (e && e[0]) || ''
      this.form.end_time = (e && e[1]) || ''
    },
    // 分类树选中
    handleNodeCheck(data) {
      const resultChecked = this.$refs.tree.getCheckedNodes()
      this.form.tree = resultChecked.map((e) => {
        return e.id
      })
    },
    // 图集
    handleImageListUploadChange(result) {
      this.form.image_list = result.imageList.map((item) => {
        return { id: item.id, name: item.name, description: item.description, path: item.path, url: item.url }
      })
    },
    // 联级分类选择
    handleCascaderCategoryTreeChange(e) {
      this.form.category_id = e && e.length > 0 ? e[e.length - 1] : 0
    }
  }
}
</script>

<style scoped lang="scss">
</style>

